//
//  YBGoodsListVC.m
//  WuyouTang
//
//  Created by YB007 on 2020/8/29.
//  Copyright © 2020 cat. All rights reserved.
//

#import "YBGoodsListVC.h"
#import "WuyouTangAddGoodsVC.h"
#import "YBGoodsInfoVC.h"
@interface YBGoodsListVC ()<UICollectionViewDelegate,UICollectionViewDataSource>
{
    int _paging;
    NSString *_allGoodsNum;
    CGFloat _headerH;
}
@property(nonatomic,strong)NSDictionary *shopInfo;
@property(nonatomic,strong)NSMutableArray *dataArray;
@property(nonatomic,strong)UICollectionView *collectionView;

@property(nonatomic,strong)UIView *headerView;
@property(nonatomic,strong)UIImageView *avatarEffect;
@property(nonatomic,strong)UIImageView *shopCoverIV;
@property(nonatomic,strong)UILabel *shopNameL;
@property(nonatomic,strong)UILabel *shopDesL;
@property(nonatomic,strong)UILabel *shopPhoneL;
@property(nonatomic,strong)UILabel *shopGoodsNumL;

@property(nonatomic,strong)UIButton *addGoodsBtn;       //只有自己的商铺

@end

@implementation YBGoodsListVC

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self pullData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = RGB_COLOR(@"#f5f5f5", 1);
    self.naviView.hidden = YES;
    self.dataArray = [NSMutableArray array];
    _headerH = 175;
    _paging = 1;
    [self.view addSubview:self.headerView];
    [self.view addSubview:self.collectionView];
    
    if (_enterType == GoodsEnterType_Shop && [_touserID isEqual:[Config getOwnID]]) {
        [self.view addSubview:self.addGoodsBtn];
        [_addGoodsBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.equalTo(self.view.mas_width).offset(-34);
            make.centerX.equalTo(self.view);
            make.height.mas_equalTo(38);
            make.bottom.equalTo(self.view.mas_bottom).offset(-ShowDiff-15);
        }];
    }
    
}
-(void)pullData {
    
    NSString *url = @"Shop.getShop";
    if (_enterType == GoodsEnterType_Live || _enterType == GoodsEnterType_Publish) {
        url = @"Shop.getShopGoodsList";
    }
    YBWeakSelf;
    [WYNetworking postWithUrl:url Dic:@{@"p":@(_paging),@"touid":_touserID} Suc:^(int code, id info, NSString *msg) {
        [_collectionView.mj_header endRefreshing];
        [_collectionView.mj_footer endRefreshing];
        if (code == 0) {
            NSDictionary *infoDic = [info firstObject];
            _shopInfo = [infoDic valueForKey:@"shopinfo"];
            _allGoodsNum = minstr([infoDic valueForKey:@"nums"]);
            [weakSelf setHeaderData];
            NSArray *listA = [infoDic valueForKey:@"list"];
            if (_paging == 1) {
                [_dataArray removeAllObjects];
            }
            if (listA <= 0) {
                [_collectionView.mj_footer endRefreshingWithNoMoreData];
            }else {
                [_dataArray addObjectsFromArray:listA];
            }
            if (_dataArray.count <=0 ) {
                [PublicView showTextNoData:_collectionView text1:@"" text2:YZMsg(@"暂无数据") centerY:0.7];
            }else {
                [PublicView hiddenTextNoData:_collectionView];
            }
            [_collectionView reloadData];
        }else{
            [MBProgressHUD showPop:msg];
        }
    } Fail:^(id fail) {
        [_collectionView.mj_header endRefreshing];
        [_collectionView.mj_footer endRefreshing];
    }];
    
}
- (UIView *)headerView {
    if (!_headerView) {
        
        _headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, _window_width, _headerH+statusbarHeight)];
        
        _avatarEffect = [[UIImageView alloc]initWithFrame:_headerView.bounds];
        _avatarEffect.contentMode = UIViewContentModeScaleAspectFill;
        _avatarEffect.clipsToBounds = YES;
        _avatarEffect.userInteractionEnabled = YES;
        UIBlurEffect *blur = [UIBlurEffect effectWithStyle:UIBlurEffectStyleDark];
        UIVisualEffectView *effectview = [[UIVisualEffectView alloc] initWithEffect:blur];
        effectview.frame = _headerView.bounds;
        [_avatarEffect addSubview:effectview];
        [_headerView addSubview:_avatarEffect];
        
        
        UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        backBtn.frame = CGRectMake(0, 24+statusbarHeight, 40, 40);
        [backBtn setImage:[UIImage imageNamed:@"pub_back"] forState:0];
        [backBtn addTarget:self action:@selector(clickBack) forControlEvents:UIControlEventTouchUpInside];
        [_headerView addSubview:backBtn];
        
        _shopCoverIV = [[UIImageView alloc]init];
        _shopCoverIV.layer.cornerRadius = 5;
        _shopCoverIV.layer.masksToBounds = YES;
        _shopCoverIV.contentMode = UIViewContentModeScaleAspectFill;
        _shopCoverIV.clipsToBounds = YES;
        [_headerView addSubview:_shopCoverIV];
        [_shopCoverIV mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(_headerView.mas_left).offset(20);
            make.width.height.mas_equalTo(_headerH*0.5);
            make.bottom.equalTo(_headerView.mas_bottom).offset(-16);
        }];
        
        _shopNameL = [[UILabel alloc]init];
        _shopNameL.font = [UIFont boldSystemFontOfSize:15];
        _shopNameL.textColor = UIColor.whiteColor;
        [_headerView addSubview:_shopNameL];
        [_shopNameL mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(_shopCoverIV.mas_right).offset(15);
            make.right.equalTo(_headerView.mas_right).offset(-20);
            make.top.equalTo(_shopCoverIV);
        }];
        
        _shopDesL = [[UILabel alloc]init];
        _shopDesL.textColor = RGB_COLOR(@"#C8C8C8", 1);
        _shopDesL.font = SYS_Font(11);
        _shopDesL.numberOfLines = 2;
        [_headerView addSubview:_shopDesL];
        [_shopDesL mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(_shopNameL);
            make.top.equalTo(_shopNameL.mas_bottom).offset(8);
            make.right.lessThanOrEqualTo(_headerView.mas_right).offset(-20);
        }];
        
        _shopPhoneL = [[UILabel alloc]init];
        _shopPhoneL.textColor = RGB_COLOR(@"#C8C8C8", 1);
        _shopPhoneL.font = SYS_Font(11);
        _shopPhoneL.numberOfLines = 2;
        [_headerView addSubview:_shopPhoneL];
        [_shopPhoneL mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(_shopNameL);
            make.top.equalTo(_shopDesL.mas_bottom).offset(5);
            make.right.lessThanOrEqualTo(_headerView.mas_right).offset(-20);
        }];
        
        
        _shopGoodsNumL = [[UILabel alloc]init];
        _shopGoodsNumL.textColor = RGB_COLOR(@"#C8C8C8", 1);
        _shopGoodsNumL.font = SYS_Font(11);
        [_headerView addSubview:_shopGoodsNumL];
        [_shopGoodsNumL mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(_shopNameL);
            make.bottom.equalTo(_shopCoverIV.mas_bottom);
        }];
        
        
    }
    return _headerView;
}
-(void)setHeaderData {
    [_shopCoverIV sd_setImageWithURL:[NSURL URLWithString:minstr([_shopInfo valueForKey:@"thumb"])]];
    [_avatarEffect sd_setImageWithURL:[NSURL URLWithString:minstr([_shopInfo valueForKey:@"thumb"])] placeholderImage:[PublicObj getAppIcon]];
    _shopNameL.text = minstr([_shopInfo valueForKey:@"name"]);
    _shopDesL.text = minstr([_shopInfo valueForKey:@"des"]);
    _shopPhoneL.text = [NSString stringWithFormat:@"%@ %@",YZMsg(@"联系方式"),[_shopInfo valueForKey:@"tel"]];
    _shopGoodsNumL.text = _allGoodsNum;
}
-(void)clickBack {
    if (_enterType == GoodsEnterType_Live && self.refreshEvent) {
        self.refreshEvent();
    }
    [self.navigationController popViewControllerAnimated:YES];
}


#pragma mark - CollectionView 代理

// * minimumLineSpacing、minimumInteritemSpacing去设置
// -(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
// return CGSizeMake(0,0);
// }
// -(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
// {
// return UIEdgeInsetsMake(2,2,2,2);
// }
//
//- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
//    return 0.01;
//}
//- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
//    return 0.01;
//}
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return _dataArray.count;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    YBGoodsListCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"YBGoodsListCell" forIndexPath:indexPath];
    NSDictionary *subDic = _dataArray[indexPath.row];
    cell.touserID = _touserID;
    cell.enterType = _enterType;
    cell.dataDic = subDic;
    
    //这里只判断发布视频关联商品 -- 直播中的在售商品 在cell中根据 issale 判断选中状态;
    if (_enterType == GoodsEnterType_Publish) {
        if (_selGoodsList.count>0) {
            cell.selFlagView.hidden = YES;
            for (NSDictionary *pSelDic in _selGoodsList) {
                if ([[pSelDic valueForKey:@"id"] isEqual:[subDic valueForKey:@"id"]]) {
                    /*
                    cell.selFlagIV.hidden = NO;
                    cell.bgView.layer.borderColor = Pink_Cor.CGColor;
                    */
                    cell.selFlagView.hidden = NO;
                }else{
                    /*
                    cell.selFlagIV.hidden = YES;
                    cell.bgView.layer.borderColor = UIColor.clearColor.CGColor;
                     */
                    cell.selFlagView.hidden = YES;
                }
            }
        }else {
            /*
            cell.selFlagIV.hidden = YES;
            cell.bgView.layer.borderColor = UIColor.clearColor.CGColor;
             */
            cell.selFlagView.hidden = YES;
        }
    }
    return cell;
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    NSDictionary *subDic = _dataArray[indexPath.row];
    switch (_enterType) {
        case GoodsEnterType_Shop:{
            YBGoodsInfoVC *infoVC = [[YBGoodsInfoVC alloc]init];
            infoVC.infoType = InfoEnterType_GList;
            infoVC.touserID = _touserID;
            infoVC.goodsID = minstr([subDic valueForKey:@"id"]);
            [[YBBaseAppDelegate sharedAppDelegate]pushViewController: infoVC animated:YES];
        }break;
        case GoodsEnterType_Live:{
            NSString *oldIssale = minstr([subDic valueForKey:@"issale"]);
            //原来选中-->非选中
            //原来非选中-->选中
            NSString *newIsSale = [oldIssale isEqual:@"1"]?@"0":@"1";
            [MBProgressHUD showMessage:@""];
            [WYNetworking postWithUrl:@"Shop.setSale" Dic:@{@"goodsid":minstr([subDic valueForKey:@"id"]),@"issale":newIsSale} Suc:^(int code, id info, NSString *msg) {
                [MBProgressHUD hideHUD];
                [MBProgressHUD showPop:msg];
                if (code == 0) {
                    NSDictionary *m_dic = [NSMutableDictionary dictionaryWithDictionary:subDic];
                    [m_dic setValue:newIsSale forKey:@"issale"];
                    NSDictionary *newDic = [NSDictionary dictionaryWithDictionary:m_dic];
                    [_dataArray replaceObjectAtIndex:indexPath.row withObject:newDic];
                    [collectionView reloadItemsAtIndexPaths:@[indexPath]];
                }
            } Fail:^(id fail) {
                [MBProgressHUD hideHUD];
            }];
            
        }break;
        case GoodsEnterType_Publish:{
            
            NSDictionary *oldDic = @{};
            if (_selGoodsList.count > 0) {
                oldDic = _selGoodsList[0];
            }
            BOOL isSel = YES;
            NSDictionary *newDic = subDic.copy;
            if ([oldDic allKeys].count >0) {
                isSel = NO;
                newDic = @{}.copy;
            }
            if (self.publishEvent) {
                self.publishEvent(isSel,newDic);
            }
            _selGoodsList = @[newDic];
            [collectionView reloadData];
            //要求不要自动返回
            //[self.navigationController popViewControllerAnimated:YES];
        }break;
        case GoodsEnterType_GoodInfo:{
            if (self.infoBakcEvent) {
                self.infoBakcEvent(subDic);
            }
            [self.navigationController popViewControllerAnimated:YES];
        }break;
            
        default:
            break;
    }
    
}

#pragma mark - set/get
- (UICollectionView *)collectionView {
    if (!_collectionView) {
        UICollectionViewFlowLayout *flow = [[UICollectionViewFlowLayout alloc]init];
        flow.scrollDirection = UICollectionViewScrollDirectionVertical;
        flow.itemSize = CGSizeMake(_window_width/2-1, (_window_width/2-1) + 60);
        flow.minimumLineSpacing = 2;
        flow.minimumInteritemSpacing = 2;
        _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0,statusbarHeight+_headerH, _window_width, _window_height-_headerH-statusbarHeight) collectionViewLayout:flow];
        [_collectionView registerNib:[UINib nibWithNibName:@"YBGoodsListCell" bundle:nil] forCellWithReuseIdentifier:@"YBGoodsListCell"];
        _collectionView.delegate =self;
        _collectionView.dataSource = self;
        _collectionView.mj_footer  = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
            _paging ++;
            [self pullData];
        }];
        _collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            _paging = 1;
            [self pullData];
        }];
        
        if (_enterType == GoodsEnterType_Shop && [_touserID isEqual:[Config getOwnID]]) {
            _collectionView.contentInset = UIEdgeInsetsMake(0, 0, ShowDiff+60, 0);
        }else{
            _collectionView.contentInset = UIEdgeInsetsMake(0, 0, ShowDiff, 0);
        }
        _collectionView.backgroundColor = RGB_COLOR(@"#f5f5f5", 1);
    }
    return _collectionView;
}

- (UIButton *)addGoodsBtn {
    if (!_addGoodsBtn) {
        _addGoodsBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _addGoodsBtn.backgroundColor = Pink_Cor;
        [_addGoodsBtn setTitle:YZMsg(@"+上传商品") forState:0];
        _addGoodsBtn.titleLabel.font = SYS_Font(13);
        _addGoodsBtn.layer.cornerRadius = 8;
        _addGoodsBtn.layer.masksToBounds = YES;
        [_addGoodsBtn setTitleColor:UIColor.whiteColor forState:0];
        [_addGoodsBtn addTarget:self action:@selector(clikcAddGoodsBtn) forControlEvents:UIControlEventTouchUpInside];
    }
    return _addGoodsBtn;
}

-(void)clikcAddGoodsBtn {
    WuyouTangAddGoodsVC *addVC = [[WuyouTangAddGoodsVC alloc]init];
    YBWeakSelf;
    addVC.addRefreshEvnet = ^{
        [weakSelf pullData];
    };
    [[YBBaseAppDelegate sharedAppDelegate]pushViewController:addVC animated:YES];
}
@end
